package cn.schoolwow.util.module.crypto.cipher.aes.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String mode = flowContext.checkData("mode", String.class);

        switch (mode){
            case "encrypt":{encrypt(flowContext);}break;
            case "decrypt":{decrypt(flowContext);}break;
        }
    }

    @Override
    public String name() {
        return "AES算法加解密";
    }

    private void encrypt(FlowContext flowContext) throws Exception{
        String secretKey = flowContext.checkData("secretKey", String.class);
        String plainText = flowContext.checkData("plainText", String.class);

        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        String base64String = Base64.getEncoder().encodeToString(encrypted);
        flowContext.putReturnData("string", base64String);
    }

    private void decrypt(FlowContext flowContext) throws Exception{
        String secretKey = flowContext.checkData("secretKey", String.class);
        String encryptText = flowContext.checkData("encryptText", String.class);

        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decoded = Base64.getDecoder().decode(encryptText);
        byte[] decrypted = cipher.doFinal(decoded);
        String plainText = new String(decrypted, StandardCharsets.UTF_8);
        flowContext.putReturnData("string", plainText);
    }
}
